<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Admin extends MY_Controller {
    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;
    /**
     * @var ConsumerPromotionModel
     */
    public $mPromotion = null;
    /**
     * @var MerchantBalanceModel
     */
    public $mBalance = null;
    /**
     * @var ConsumerBuyModel
     */
    public $mBuy = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('ConsumerPromotionModel', 'mPromotion', 'consumer');
        $this->loadModel('MerchantBalanceModel', 'mBalance', 'merchant');
        $this->loadModel('ConsumerBuyModel', 'mBuy', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $data = array(
            'info' => $this->mOrder->getWebMoneyList(),
            'expenditure' => $this->mUser->getExpenditure(),//商家提现+用户提现+用户退款
            'buyLog' => $this->mBuy->getTotalBuyLog()//用户提现+用户退款
        );
		$this->view('statistics/admin/index', $data, 'datatable,date_range_picker');
	}

    public function getList(){
        $timeGap = trim(get('timegap'));
        if ($timeGap){
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]);
        }else{
            $startTime = 0;
            $endTime = 0;
        }
        $data = $this->mOrder->getWebMoneyList($startTime, $endTime, false);
//        $bLog = $this->mPromotion->getTotalBonusLog($startTime, $endTime);
        $merBLog = $this->mBalance->getTotalBalanceLog($startTime, $endTime, false);
        $buyLog = $this->mBuy->getTotalBuyLog($startTime, $endTime,false);
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['time'];
            $data['aaData'][$k][] = $v['product_amount'];
            $data['aaData'][$k][] = sprintf('%.2f',$v['total_amount']-$v['reality_amount']); // 优惠金额
            $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
            $data['aaData'][$k][] = $shipping_fee;
            $ban = isset($merBLog[$v['time']]['withdrawals']) ? ltrim($merBLog[$v['time']]['withdrawals'], '-') : 0;
            $blRefund = isset($buyLog[$v['time']]['refund']) ? $buyLog[$v['time']]['refund'] : 0;
            $blWithdrawals = isset($buyLog[$v['time']]['withdrawals']) ? ltrim($buyLog[$v['time']]['withdrawals'], '-') : 0;
            $expenditure = round($ban+$blRefund+$blWithdrawals, 2);
            $precipitatedFunds = $v['product_amount']+$shipping_fee-$expenditure; // 平台沉淀资金
            $data['aaData'][$k][] = $expenditure;
            $data['aaData'][$k][] = round($precipitatedFunds, 2);
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '查看详情',
                'attr' => array(
                    'href' => getUrl('statistics/admin/details?time='.$v['time']),
                    'class' => 'btn green-stripe btn-xs default'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'statistics',
                    'key' => 'admin-view'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);

    }

    /**
     * 明细
     */
    public function details(){
        $time = get('time');
        if (!$time){
            show_404();
        }

        $data = array(
            'time' => $time,
            'title' => '明细'
        );
        $this->view('statistics/admin/details', $data, 'datatable,validation,region,select2');
    }

    public function detailsGetList(){
         $time = trim(get('time'));
        $data = $this->mOrder->getOrderListByTime($time);
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = '';
            $data['aaData'][$k][] = $v['id'];
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $v['product_amount'];
            $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
            $data['aaData'][$k][] = $shipping_fee;
            $data['aaData'][$k][] = $v['total_amount'];
            $data['aaData'][$k][] = sprintf('%.2f',$v['total_amount']-$v['product_amount']); // 优惠金额
            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 根据时间获取信息
     */
    public function getStatistics(){
        $timeGap = trim(post('timegap'));
        if (!$timeGap){
            $this->ajaxReturn(0, '请选择时间');
        }
        $timeGapArr = explode(' - ', $timeGap);
        $startTime = strtotime($timeGapArr[0]);
        $endTime = strtotime($timeGapArr[1]);

        $info = $this->mOrder->getWebMoneyList($startTime, $endTime);
        $expenditure = $this->mUser->getExpenditure($startTime, $endTime);
        $data = array(
            'reality_amount' => $info['reality_amount'],
            'total' => $info['total'],
            'expenditure' =>$expenditure,
            'profit' => round($info['reality_amount']-$expenditure, 2),
        );
        $this->ajaxReturn(1, '', $data);
    }

    /**
     * 导出
     * @author defcu
     */
    public function export(){
        $timeGap = trim(get('timegap'));
        if ($timeGap){
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]);
            $name = $startTime.'-'.$endTime;
        }else{
            $startTime = 0;
            $endTime = 0;
            $name = date('Y-m-d', time());
        }
        $filename = '平台资金信息'.$name.'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('时间,订单商品总额,订单优惠总额,物流总额,支出,平台沉淀资金',
                'gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $list = $this->mOrder->getWebMoneyList($startTime, $endTime, false,$page,$pageNumber);
            $merBLog = $this->mBalance->getTotalBalanceLog($startTime, $endTime, false,$page,$pageNumber);
            $buyLog = $this->mBuy->getTotalBuyLog($startTime, $endTime,false,$page,$pageNumber);

            if(empty($list)){
                break;
            }
            $page ++;
            foreach($list as $v){
                $discount = sprintf('%.2f',$v['total_amount']-$v['reality_amount']); // 优惠金额
                $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
                $ban = isset($merBLog[$v['time']]) ? ltrim($merBLog[$v['time']]['withdrawals'], '-') : 0;
                $blRefund = isset($buyLog[$v['time']]) ? $buyLog[$v['time']]['refund'] : 0;
                $blWithdrawals = isset($buyLog[$v['time']]) ? ltrim($buyLog[$v['time']]['withdrawals'], '-') : 0;
                $aM = sprintf('%.2f',$ban)+sprintf('%.2f',$blRefund)+sprintf('%.2f',$blWithdrawals);
                $expenditure = $aM; // 支出
                $precipitatedFunds = sprintf('%.2f',$v['product_amount']+$shipping_fee-$expenditure); // 平台沉淀资金

                echo mb_convert_encoding($v['time'].','.$v['product_amount'].','.$discount.','.
                        $shipping_fee.','.$expenditure.','.$precipitatedFunds, 'gb2312','utf-8')."\n";
            }
        }
    }

    /**
     * 导出详情
     */
    public function detailExport(){
        $filename = '平台资金-订单详情'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('订单id,订单号,会员手机,商品总价,物流价格,订单总价,订单优惠,下单日期','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        $time = trim(get('time'));

        while(true){
            $data = $this->mOrder->getOrderListByTime($time, array('page' => $page, 'pageNumber' => $pageNumber));
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
                $amount = sprintf('%.2f',$v['total_amount']-$v['product_amount']); // 优惠金额
                $addtime = dateFormat($v['addtime'], true);
                echo mb_convert_encoding($v['id']."\t".','.$v['code']."\t".','.$v['mobile']."\t".','.$v['product_amount']."\t".','.$shipping_fee.','.$v['total_amount'].','.$amount.','.$addtime, 'gb2312','utf-8')."\n";
            }
        }
        echo mb_convert_encoding('时间：'.$time, 'gb2312','utf-8')."\n";
    }
}
